<template>
  <div class="operation-logs-container">
    <!-- 搜索表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      class="search-form"
    >
      <el-form-item label="操作模块" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入操作模块"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="操作人员" prop="operatorName">
        <el-input
          v-model="queryParams.operatorName"
          placeholder="请输入操作人员"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="businessType">
        <el-select
          v-model="queryParams.businessType"
          placeholder="操作类型"
          clearable
          style="width: 200px"
        >
          <el-option label="新增" :value="1" />
          <el-option label="修改" :value="2" />
          <el-option label="删除" :value="3" />
          <el-option label="查询" :value="4" />
          <el-option label="导出" :value="5" />
          <el-option label="导入" :value="6" />
          <el-option label="其他" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="操作状态"
          clearable
          style="width: 200px"
        >
          <el-option label="成功" :value="1" />
          <el-option label="失败" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 340px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb-4">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
          >批量删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleCleanAll"
          >清空所有</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="logsList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column
        label="操作模块"
        prop="title"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="操作类型" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getBusinessTypeTagType(scope.row.businessType)">
            {{ getBusinessTypeName(scope.row.businessType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作人员" prop="operatorName" width="120" />
      <el-table-column
        label="操作IP"
        prop="operatorIp"
        width="130"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作地点"
        prop="operatorLocation"
        width="130"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="操作状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? "成功" : "失败" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作时间"
        align="center"
        prop="operatorTime"
        width="180"
      >
        <template #default="scope">
          {{ formatDateTime(scope.row.operatorTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)"
              >详情</el-button
            >
            <el-divider direction="horizontal" />
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              class="delete-button"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.size"
        :current-page="queryParams.current"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="操作日志详情"
      v-model="dialogVisible"
      width="700px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="操作模块">{{
          currentRow.title
        }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{
          getBusinessTypeName(currentRow.businessType)
        }}</el-descriptions-item>
        <el-descriptions-item label="操作人员">{{
          currentRow.operatorName
        }}</el-descriptions-item>
        <el-descriptions-item label="请求方式">{{
          currentRow.requestMethod
        }}</el-descriptions-item>
        <el-descriptions-item label="操作地点">{{
          currentRow.operatorLocation
        }}</el-descriptions-item>
        <el-descriptions-item label="操作状态">
          <el-tag :type="currentRow.status === 0 ? 'success' : 'danger'">
            {{ currentRow.status === 0 ? "成功" : "失败" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{
          currentRow.operatorTime
        }}</el-descriptions-item>
        <el-descriptions-item label="消耗时间"
          >{{ currentRow.costTime }} 毫秒</el-descriptions-item
        >
        <el-descriptions-item label="请求URL" :span="2">{{
          currentRow.operatorUrl
        }}</el-descriptions-item>
        <el-descriptions-item label="请求参数" :span="2">
          <div class="code-block">
            {{ formatJson(currentRow.operatorParam) }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="返回结果" :span="2">
          <div class="code-block">{{ formatJson(currentRow.jsonResult) }}</div>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="currentRow.status === 1"
          label="错误消息"
          :span="2"
        >
          <div class="error-msg">{{ currentRow.errorMsg }}</div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOperationLogs,
  deleteOperationLog,
  cleanOperationLog,
} from "@/api/logControl";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "OperationLogsTab",
  data() {
    return {
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        title: undefined,
        operatorName: undefined,
        businessType: undefined,
        status: undefined,
        operatorTime: undefined,
      },
      // 日期范围
      dateRange: [],
      // 表格数据
      logsList: [],
      // 加载状态
      loading: false,
      // 总条数
      total: 0,
      // 选中的ID数组
      selectedIds: [],
      // 当前查看的行
      currentRow: {},
      // 对话框可见性
      dialogVisible: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 格式化日期时间(去掉T)
    formatDateTime(dateTime) {
      if (!dateTime) return "";

      try {
        // 将ISO日期格式转换为标准格式
        const date = new Date(dateTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (e) {
        console.error("日期格式化错误:", e);
        return dateTime; // 如果出错返回原始值
      }
    },
    // 获取操作日志列表
    getList() {
      this.loading = true;
      // 处理日期范围
      const params = { ...this.queryParams };
      if (this.dateRange && this.dateRange.length === 2) {
        params.operatorTime = this.dateRange[0] + " - " + this.dateRange[1];
      }

      getOperationLogs(params.current, params.size, params)
        .then((res) => {
          if (res.data && res.data.success) {
            const data = res.data.data;
            this.logsList = data.records || [];
            this.total = data.total || 0;
          } else {
            this.logsList = [];
            this.total = 0;
            ElMessage.error(res.data?.message || "获取操作日志失败");
          }
        })
        .catch((err) => {
          console.error("获取操作日志出错:", err);
          ElMessage.error("获取操作日志出错");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 搜索按钮
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },

    // 重置按钮
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    // 每页条数改变
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(current) {
      this.queryParams.current = current;
      this.getList();
    },

    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },

    // 查看详情
    handleViewDetail(row) {
      this.currentRow = row;
      this.dialogVisible = true;
    },

    // 删除单条日志
    handleDelete(row) {
      ElMessageBox.confirm(
        `是否确认删除操作模块为"${row.title}"的日志?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteOperationLog(row.id)
            .then((res) => {
              if (res.data && res.data.success) {
                ElMessage.success("删除成功");
                this.getList();
              } else {
                ElMessage.error(res.data?.message || "删除失败");
              }
            })
            .catch(() => {
              ElMessage.error("删除操作出错");
            });
        })
        .catch(() => {});
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        ElMessage.warning("请至少选择一条记录");
        return;
      }

      ElMessageBox.confirm(
        `是否确认删除选中的 ${this.selectedIds.length} 条日志记录?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteOperationLog(this.selectedIds.join(","))
            .then((res) => {
              if (res.data && res.data.success) {
                ElMessage.success("批量删除成功");
                this.getList();
              } else {
                ElMessage.error(res.data?.message || "批量删除失败");
              }
            })
            .catch(() => {
              ElMessage.error("批量删除操作出错");
            });
        })
        .catch(() => {});
    },

    // 清空所有日志
    handleCleanAll() {
      ElMessageBox.confirm("是否确认清空所有操作日志?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          cleanOperationLog()
            .then((res) => {
              if (res.data && res.data.success) {
                ElMessage.success("清空操作日志成功");
                this.getList();
              } else {
                ElMessage.error(res.data?.message || "清空操作日志失败");
              }
            })
            .catch(() => {
              ElMessage.error("清空操作日志出错");
            });
        })
        .catch(() => {});
    },

    // 获取业务类型名称
    getBusinessTypeName(type) {
      const typeMap = {
        0: "其他",
        1: "新增",
        2: "修改",
        3: "删除",
        4: "查询",
        5: "导出",
        6: "导入",
      };
      return typeMap[type] || "未知";
    },

    // 获取业务类型标签样式
    getBusinessTypeTagType(type) {
      const typeMap = {
        0: "info",
        1: "success",
        2: "warning",
        3: "danger",
        4: "info",
        5: "info",
        6: "info",
      };
      return typeMap[type] || "info";
    },

    // 格式化JSON
    formatJson(jsonString) {
      if (!jsonString) return "";
      try {
        const json = JSON.parse(jsonString);
        return JSON.stringify(json, null, 2);
      } catch (e) {
        return jsonString;
      }
    },
  },
};
</script>

<style scoped>
.operation-logs-container {
  padding: 10px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.mb-4 {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.code-block {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  max-height: 200px;
  overflow: auto;
  font-family: monospace;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
}

.error-msg {
  color: #f56c6c;
  word-break: break-all;
}
.operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.operation-buttons .el-divider {
  margin: 4px 0;
}

.delete-button {
  color: #f56c6c;
}

.delete-button:hover {
  color: #f78989;
}
</style>